package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.Permission;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @ClassName IndexController
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-08-19 15:11
 * @Version 1.0
 */
@Controller
public class IndexController {

    @Reference
    private AdminService adminService;

    @Reference
    private PermissionService permissionService;

    @RequestMapping
    public String toIndex(Model model){
        //从SpringSecurity的上下文中获取当前用户的认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        //当前登录用户id,后续替换
        //Long adminId = 1L;
        Admin admin = adminService.getByUsername(user.getUsername());
        List<Permission> permissionList = permissionService.findMenuPermissionByAdminId(admin.getId());
        model.addAttribute("admin",admin);
        model.addAttribute("permissionList",permissionList);
        return "frame/index";
    }

    @RequestMapping("/main")
    public String toMain(){
        return "frame/main";
    }

    @RequestMapping("/loginPage")
    public String login(){
        return "frame/login";
    }

    //获取当前登录用户的权限信息
    @RequestMapping("getInfo")
    @ResponseBody
    public Object getInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getPrincipal();
    }

    //自定义无权限访问页面
    @RequestMapping("/auth")
    public String auth(){
        return "frame/auth";
    }
}